let app = getApp();

Page({
  data: {
    showState: false,
    detailShow: false,
    titleShowState: true,
    shop: {
      logo: '../../../assets/images/banner03.jpg',
      shopName: '小明零食',
      notice: '小明明小小小小明明小明明明明小小小小明明小小小小明明小小小',
      shopId: '',
      status: 0
    },
    shops: [

    ],
    goods: {

    },
    catalogList: [

    ],
    cart: {
      count: 0,
      total: 0,
      list: {}
    },
    classifyName: '',
    classifyViewed: '',
    showCartDetail: false,
    headerHeight: 100,
    goodDetailData: {},
    enter: 'init',
    tabNavList: [],
    productList: []
  },
  onLoad: function (options) {
    if (JSON.stringify(options) != '{}') {
      if (options.enter) {
        this.setData({
          enter: options.enter
        })
        this.getQueryAdminInfo()
      }
    }
    if (app.Store.get('shopDetail')) {
      this.setData({
        "shop.status": app.Store.get('shopDetail').status,
        "shop.shopName": app.Store.get('shopDetail').shopName,
        "shop.shopId": app.Store.get('shopDetail').shopId,
        "shop.logo": app.Store.get('shopDetail').logo,
        "shop.notice": app.Store.get('shopDetail').notice
      })
    }
    this.getData()
  },
  getGoodsSortList(shopId) {//商品分类列表
    let _this = this
    let url = this.data.enter === 'user' ? app.Api.CatalogIndex : app.Api.CatalogList
    let obj = {
      shopId: shopId
    }
    app.Http.http({
      url: url,
      method: 'POST',
      params: this.data.enter === 'user' ? {} : obj
    }).then(data => {
      let resultData = data
      let nav = []
      if (resultData.length > 0) {

        if (this.data.enter === 'user') {
          resultData[0].subCategoryList.map((item) => {
            item.subCategoryList = []
          })
          _this.setData({
            tabNavList: resultData,
            catalogList: resultData[0].subCategoryList
          })

        } else {
          resultData.map((item) => {
            item.subCategoryList = []
          })
          _this.setData({
            catalogList: resultData,
            classifyName: resultData[0].name,
            classifySeleted: 'tab' + resultData[0].id
          })
        }


        this.getGoodsList({
          shopId: this.data.shop.shopId,
          catalogList: this.data.catalogList
        })
      } else {
        _this.setData({
          catalogList: []
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },
  getGoodsList(objData) {//商品列表
    let _this = this
    let url = this.data.enter === 'user' ? app.Api.AdminProducts : app.Api.ShopProducts
    if (objData.catalogList.length > 0) {
      let reqObj = {
        shopId: objData.shopId
      }
      let obj = {}
      app.Http.http({
        url: url,
        method: 'POST',
        params: this.data.enter === 'user' ? {} : reqObj
      }).then(data => {

        if (data.length > 0) {
          objData.catalogList.map((item) => {//分类
            data.map((item1, key1, ary1) => {//商品
              if (item.id === item1.category_id) {//当前分类下的商品
                if (item.subCategoryList.length > 0) {
                  item.subCategoryList.map((item2) => {
                    if (item2 != item1.id) {
                      item.subCategoryList.push(item1.id)
                      item.subCategoryList = [...new Set(item.subCategoryList)]
                      obj[item1.id] = item1
                    }
                  })
                } else {
                  obj[item1.id] = item1
                  item.subCategoryList.push(item1.id)
                  item.subCategoryList = [...new Set(item.subCategoryList)]
                }
              }
            })
          })
          _this.setData({
            catalogList: objData.catalogList
          })

        } else {
          obj = {}
        }

        _this.setData({
          goods: obj
        })

      }).catch(err => {
        console.log(err)
      })
    }

  },
  navSelected(e) {
    let _this = this
    let data = e.currentTarget.dataset.item
    console.log(this.data.goods)
    for (let name in this.data.goods) {
      let itemVal = this.data.goods[name]
      data.subCategoryList.map((item) => {
        if (item.id == itemVal.category_id) {
          item.subCategoryList.push(itemVal)
          item.subCategoryList = [...new Set(item.subCategoryList)]
        }
      })
    }
    console.log(this.data.catalogList)
  },
  getQueryAdminInfo() {
    app.Http.http({
      url: app.Api.QueryAdminInfo,
      method: 'POST',
      params: {}
    }).then(data => {
      this.setData({
        shop: {
          logo: data[0].platform_logo,
          shopName: data[0].platform_name,
          notice: data[0].platform_announcement
        }
      })
    }).catch(err => {
      console.log(err)
    })
  },
  getData() {
    this.getGoodsSortList(this.data.shop.shopId)
  },
  onShow: function () {

  },
  onReady() {
    let query = wx.createSelectorQuery()
    var that = this;
    query.select('#header').boundingClientRect(function (rect) {
      that.setData({
        headerHeight: rect.height
      })
    }).exec();
  },
  isShow(e) {
    let _this = this;
    this.setData({
      showState: !this.data.showState,
      titleShowState: false
    })
    // setTimeout(()=>{
    //   _this.setData({
    //     titleShowState: true
    //   })
    // },50)
    let query = wx.createSelectorQuery()
    var that = this;
    query.select('#header').boundingClientRect(function (rect) {
      that.setData({
        headerHeight: rect.height
      })
    }).exec();
  },
  close() {
    this.setData({
      detailShow: false
    })
  },
  goodDetail(e) {
    // e.stopPropagation();  
    e.cancelBubble = true
    let item = e.currentTarget.dataset.item
    let add = e.currentTarget.dataset.add

    if (add !== 'add') {
      this.setData({
        detailShow: true,
        goodDetailData: item
      })
    }

  },
  toShopDetail() {//商铺详情
    app.WxService.navigateTo('/pages/shop/detail/index')
  },
  tapAddCart: function (e) {
    let id = e.target.dataset.id
    let num = e.target.dataset.num
    if (num && Number(num) > 0) {
      this.addCart(id);
    }

  },
  tapReduceCart: function (e) {
    this.reduceCart(e.target.dataset.id);
  },
  addCart: function (id) {
    var num = this.data.cart.list[id] || 0;
    this.data.cart.list[id] = num + 1;
    this.countCart();
  },
  reduceCart: function (id) {
    var num = this.data.cart.list[id] || 0;
    if (num <= 1) {
      delete this.data.cart.list[id];
    } else {
      this.data.cart.list[id] = num - 1;
    }
    this.countCart();
  },
  countCart: function () {
    let count = 0
    let total = 0;
    let sale_price = 0
    for (var id in this.data.cart.list) {
      count += this.data.cart.list[id];
      total += this.data.goods[id].sale_price * this.data.cart.list[id];
    }
    this.data.cart.count = count;
    this.data.cart.total = total;
    this.setData({
      cart: this.data.cart
    });
  },
  follow: function () {
    this.setData({
      followed: !this.data.followed
    });
  },
  onGoodsScroll: function (e) {
    let catalogList = this.data.catalogList

    if (e.detail.scrollTop > 10 && !this.data.scrollDown) {
      this.setData({
        scrollDown: true
      });
    } else if (e.detail.scrollTop < 10 && this.data.scrollDown) {
      this.setData({
        scrollDown: false
      });
    }

    var scale = e.detail.scrollWidth / 570,
      scrollTop = e.detail.scrollTop / scale,
      h = 0,
      classifySeleted,
      len = this.data.catalogList.length;
    this.data.catalogList.forEach(function (classify, i) {
      var _h = 70 + classify.subCategoryList.length * (46 * 3 + 20 * 2);
      if (scrollTop >= h - 100 / scale) {
        classifySeleted = 'tab' + classify.id;
      }
      h += _h;
    });
    this.setData({
      classifySeleted: classifySeleted,
      titleShowState: true
    });
    catalogList.map((item) => {
      if ('tab' + item.id === classifySeleted) {
        this.setData({
          classifyName: item.name
        })
      }
    })
  },
  tapClassify: function (e) {
    var id = e.target.dataset.id;
    var name = e.target.dataset.name;
    this.setData({
      classifyViewed: id,
      classifyName: name
    });
    var self = this;
    setTimeout(function () {
      self.setData({
        classifySeleted: id
      });
    }, 100);

  },
  showCartDetail: function () {
    this.setData({
      showCartDetail: !this.data.showCartDetail
    });
  },
  hideCartDetail: function () {
    this.setData({
      showCartDetail: false
    });
  },
  submit() {
    let orderList = []
    if (this.data.cart.count > 0) {
      for (let name in this.data.cart.list) {
        orderList.push({
          id: this.data.goods[name].id,
          name: this.data.goods[name].name,
          primary_pic_url: this.data.goods[name].primary_pic_url,
          sale_price: this.data.goods[name].sale_price
        })
      }
      app.Store.set("cart", this.data.cart)
      app.Store.set("confirm", orderList)
      app.WxService.navigateTo('/pages/order/confirm/index', { enterType: this.data.enter })
    } else {
      wx.showToast({
        title: '请先添加商品',
        icon: 'warning',
        duration: 10000,
        mask: !0,
      })
    }

    setTimeout(() => {
      wx.hideToast()
    }, 1000)
  },
  changeData(data) {
    this.getData()
  }
});

